package com.qzsoft.system.modules.permission.user.common;

import com.qzsoft.system.common.ConstantUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class FileUtils {
    public static String saveFile(MultipartFile[] files) {
        String headUrl = null;
        if (files != null && files.length > 0) {
            //获取年份
//            Calendar date = Calendar.getInstance();
//            String year = String.valueOf(date.get(Calendar.YEAR));
            for (MultipartFile file : files) {
                String filePath = ConstantUtils.UPLOAD_PATH;

                String uuid = UUID.randomUUID().toString();
                String fileName = file.getOriginalFilename();
                String suffix = "." + fileName.substring(fileName.lastIndexOf(".") + 1);
                uuid += suffix;
//                String dir = year + "/" +uuid;
//                uuid = year +"/"+ uuid;
                headUrl = ConstantUtils.LOCAL_HOST_ADDR + ConstantUtils.UPLOAD_MAPPING_PATH +"/" + uuid;
                System.out.println("headUrl:" + headUrl);
                String fileLocation = filePath + "/" + uuid;
                System.out.println("filePath:" + fileLocation);
                File imgFile = new File(fileLocation);

                if (!imgFile.getParentFile().exists()) {
                    imgFile.getParentFile().mkdirs();
                }
                try {
                    file.transferTo(imgFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return headUrl;
    }
}